#include "ConfigItemWidget.h"
#include <QApplication>
#include <QPainter>
#include <QDebug>
#include <QFont>
#include <QResizeEvent>

ConfigItemWidget::ConfigItemWidget(const QString &title, QWidget *parent)
    : CommonContainer(title, false, 2, parent)
    , m_isEditMode(false)
    , m_nextRow(0)
    , m_nextColumn(0)
    , m_maxColumns(10)
{
    setupUI();
    setupConnections();
}

ConfigItemWidget::~ConfigItemWidget()
{
    for (ConfigItem *item : m_configItems) {
        delete item;
    }
    m_configItems.clear();
    m_configItemMap.clear();
    
    for (MultiConfigItem *multiItem : m_multiConfigItems) {
        delete multiItem;
    }
    m_multiConfigItems.clear();
    m_multiConfigItemMap.clear();
}

void ConfigItemWidget::setupUI()
{
    QFrame *contentWt = new QFrame();
    contentWt->setObjectName("containerContent");
    m_gridLayout = new QGridLayout(contentWt);
    m_gridLayout->setContentsMargins(10, 10, 10, 10);
    m_gridLayout->setHorizontalSpacing(12);  // 增加水平间距
    m_gridLayout->setVerticalSpacing(16);    // 减少垂直间距
    m_gridLayout->setColumnStretch(0, 0);    // 第一列不拉伸
    m_gridLayout->setColumnStretch(1, 1);    // 第二列拉伸
    m_gridLayout->setColumnStretch(2, 1);    // 第三列拉伸
    m_gridLayout->setColumnStretch(3, 1);    // 第四列拉伸
    m_gridLayout->setColumnStretch(4, 1);    // 第五列拉伸
    
    setContentWidget(contentWt);
}

void ConfigItemWidget::setupConnections()
{
}

void ConfigItemWidget::addStretch()
{
    QWidget *stretchWidget = new QWidget();
    stretchWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    
    int rowCount = m_gridLayout->rowCount();
    m_gridLayout->addWidget(stretchWidget, rowCount, 0, 1, m_gridLayout->columnCount());
}

void ConfigItemWidget::addRowStretch(int row, int column)
{
    QWidget *stretchWidget = new QWidget();
    stretchWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    
    // 确保列拉伸属性已设置
    m_gridLayout->setColumnStretch(column, 1);
    
    m_gridLayout->addWidget(stretchWidget, row, column);
}

void ConfigItemWidget::addConfigItem(const QString &name, ConfigItemType type, const QString &value, 
                                   int row, int column, const QStringList &options, int columnSpan)
{
    // 检查是否已存在同名配置项
    if (m_configItemMap.contains(name)) {
        qWarning() << "ConfigItem" << name << "already exists";
        return;
    }
    
    // 确定位置
    if (row == -1) row = m_nextRow;
    if (column == -1) column = m_nextColumn;
    
    // 创建配置项
    ConfigItem *item = new ConfigItem();
    item->name = name;
    item->type = type;
    item->value = value;
    item->options = options;
    item->row = row;
    item->column = column;
    item->columnSpan = columnSpan;
    
    int currentColumn = column;
    int labelColumnSpan = 1; // 标签默认占用1列
    Qt::Alignment hAlign = Qt::AlignLeft;
    
    // 创建标签控件（除了纯标签类型）
    if (type != Label) {
        if (name.length() >= 9) {
            labelColumnSpan = 3;
            if (column != 0) {
                hAlign = Qt::AlignCenter;
            }
        }
        else if (name.length() >= 6) {
            labelColumnSpan = 2;
            if (column != 0) {
                hAlign = Qt::AlignCenter;
            }
        }
        
        item->labelWidget = new QLabel(name + ":");
        item->labelWidget->setAlignment(hAlign | Qt::AlignVCenter);
        item->labelWidget->setObjectName("configLabel");
        item->labelWidget->setMinimumWidth(80);  // 设置最小宽度而不是固定宽度
        item->labelWidget->setMaximumWidth(320); // 设置最大宽度
        if (column != 0) {
            item->labelWidget->setStyleSheet("padding-left: 8px;"); // 减少左边距
        }
        m_gridLayout->addWidget(item->labelWidget, row, currentColumn, 1, labelColumnSpan);
        currentColumn += labelColumnSpan;
    }
    
    // 添加到管理列表（在创建控件之前，因为connectWidgetSignals需要访问映射）
    m_configItems.append(item);
    m_configItemMap[name] = item;

    QLineEdit *lineEdit = new QLineEdit();
    lineEdit->setMinimumWidth(60);   // 设置最小宽度
    lineEdit->setMaximumWidth(100);  // 设置最大宽度
    lineEdit->setReadOnly(true);
    item->widget = lineEdit;
    item->widget->setObjectName(QString("configLineEdit"));
    connect(lineEdit, &QLineEdit::textChanged, this, &ConfigItemWidget::onValueChanged);
    m_gridLayout->addWidget(item->widget, row, currentColumn, 1, columnSpan);
    
    // 更新下一个位置
    m_nextColumn += (type == Label) ? columnSpan : columnSpan + labelColumnSpan;
    if (m_nextColumn >= m_maxColumns) {
        m_nextColumn = 0;
        m_nextRow++;
    }
}

void ConfigItemWidget::addMultiConfigItem(const QString &groupName, const QStringList &subItemNames, 
                                         const QStringList &subItemValues, int row, int column)
{
    // 检查是否已存在同名多配置项
    if (m_multiConfigItemMap.contains(groupName)) {
        qWarning() << "MultiConfigItem" << groupName << "already exists";
        return;
    }
    
    // 确定位置
    if (row == -1) row = m_nextRow;
    if (column == -1) column = m_nextColumn;
    
    // 创建多配置项
    MultiConfigItem *multiItem = new MultiConfigItem();
    multiItem->groupName = groupName;
    multiItem->row = row;
    multiItem->column = column;
    
    // 创建组标签
    int groupLabelColumnSpan = 1; // 组标签默认占用1列
    Qt::Alignment hAlign = Qt::AlignLeft;
    if (groupName.length() >= 9) {
        groupLabelColumnSpan = 3;
        if (column != 0) {
            hAlign = Qt::AlignCenter;
        }
    }
    else if (groupName.length() >= 6) {
        groupLabelColumnSpan = 2;
        if (column != 0) {
            hAlign = Qt::AlignCenter;
        }
    }
    
    multiItem->groupLabel = new QLabel(groupName + ":");
    multiItem->groupLabel->setAlignment(hAlign | Qt::AlignVCenter);
    multiItem->groupLabel->setObjectName("configLabel");
    multiItem->groupLabel->setMinimumWidth(80);  // 设置最小宽度
    multiItem->groupLabel->setMaximumWidth(320); // 设置最大宽度
    if (column != 0) {
        multiItem->groupLabel->setStyleSheet("padding-left: 8px;"); // 减少左边距
    }
    m_gridLayout->addWidget(multiItem->groupLabel, row, column, 1, groupLabelColumnSpan);
    
    // 创建子配置项，水平排列
    int currentColumn = column + groupLabelColumnSpan;
    for (int i = 0; i < subItemNames.size(); ++i) {
        QString rawName = subItemNames[i];
        QString subItemValue = (i < subItemValues.size()) ? subItemValues[i] : "";

        bool hideLabel = rawName.startsWith('@');
        QString subItemName = hideLabel ? rawName.mid(1) : rawName;
 
        // 创建子配置项
        ConfigItem *subItem = new ConfigItem();
        subItem->name = subItemName;
        subItem->type = LineEdit;
        subItem->value = subItemValue;
        subItem->row = row;
        subItem->column = currentColumn;
        subItem->columnSpan = 1;
        
        // 创建子标签
        if (!hideLabel && subItemName != "") {
            int subLabelColumnSpan = 1; // 子标签默认占用1列
            if (subItemName.length() >= 6) {
                subLabelColumnSpan = 2; // 如果子标签字符数大于等于6，占用2列
            }
            
            subItem->labelWidget = new QLabel(subItemName + ":");
            subItem->labelWidget->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
            subItem->labelWidget->setObjectName("configLabel");
            subItem->labelWidget->setMinimumWidth(60);  // 设置最小宽度
            subItem->labelWidget->setMaximumWidth(80);  // 设置最大宽度
            m_gridLayout->addWidget(subItem->labelWidget, row, currentColumn, 1, subLabelColumnSpan);
            currentColumn += subLabelColumnSpan;
        }
        
        // 添加到多配置项
        multiItem->subItems.append(subItem);
        
        // 添加到全局管理（在connectWidgetSignals之前）
        m_configItems.append(subItem);
        m_configItemMap[subItemName] = subItem;
        
        QLineEdit *lineEdit = new QLineEdit();
        lineEdit->setMinimumWidth(50);   // 设置最小宽度
        lineEdit->setMaximumWidth(80);   // 设置最大宽度
        lineEdit->setReadOnly(true);
        subItem->widget = lineEdit;
        connect(lineEdit, &QLineEdit::textChanged, this, &ConfigItemWidget::onValueChanged);
        m_gridLayout->addWidget(subItem->widget, row, currentColumn, 1, 1, (hideLabel || subItemName.isEmpty()) ? Qt::AlignCenter : Qt::AlignLeft);
        
        currentColumn++;
    }
    
    // 添加到多配置项管理
    m_multiConfigItems.append(multiItem);
    m_multiConfigItemMap[groupName] = multiItem;
    
    // 更新下一个位置
    m_nextColumn = currentColumn;
    if (m_nextColumn >= m_maxColumns) {
        m_nextColumn = 0;
        m_nextRow++;
    }
}

QString ConfigItemWidget::getValue(const QString &name) const
{
    ConfigItem *item = m_configItemMap.value(name);
    if (!item) return QString();
    
    switch (item->type) {
    case Label:
        return item->value;
    case LineEdit: {
        QLineEdit *edit = qobject_cast<QLineEdit*>(item->widget);
        return edit ? edit->text() : QString();
    }
    }
    
    return QString();
}

void ConfigItemWidget::setValue(const QString &name, const QString &value)
{
    ConfigItem *item = m_configItemMap.value(name);
    if (!item) return;
    
    switch (item->type) {
    case Label:
        item->value = value;
        break;
    case LineEdit: {
        QLineEdit *edit = qobject_cast<QLineEdit*>(item->widget);
        if (edit) {
            edit->setText(value);
        }
        break;
    }
    }
}

QMap<QString, QString> ConfigItemWidget::getAllValues() const
{
    QMap<QString, QString> values;
    for (const QString &name : m_configItemMap.keys()) {
        values[name] = getValue(name);
    }
    return values;
}

void ConfigItemWidget::setAllValues(const QMap<QString, QString> &values)
{
    for (auto it = values.begin(); it != values.end(); ++it) {
        setValue(it.key(), it.value());
    }
}

void ConfigItemWidget::setEditMode(bool enabled)
{
    if (m_isEditMode == enabled) return;
    
    m_isEditMode = enabled;
    
    // 设置所有控件的编辑状态
    for (ConfigItem *item : m_configItems) {
        if (item->widget) {
            item->widget->setEnabled(enabled);
            
            // 处理 QLineEdit 的只读状态
            if (item->type == LineEdit) {
                QLineEdit *lineEdit = qobject_cast<QLineEdit*>(item->widget);
                if (lineEdit) {
                    lineEdit->setReadOnly(!enabled);
                }
            }
        }
    }
    
    // 设置多配置项的编辑状态
    for (MultiConfigItem *multiItem : m_multiConfigItems) {
        for (ConfigItem *subItem : multiItem->subItems) {
            if (subItem->widget) {
                subItem->widget->setEnabled(enabled);
                
                // 处理 QLineEdit 的只读状态
                if (subItem->type == LineEdit) {
                    QLineEdit *lineEdit = qobject_cast<QLineEdit*>(subItem->widget);
                    if (lineEdit) {
                        lineEdit->setReadOnly(!enabled);
                    }
                }
            }
        }
    }
    
    emit editModeChanged(enabled);
}

bool ConfigItemWidget::isEditMode() const
{
    return m_isEditMode;
}

QWidget* ConfigItemWidget::createWidget(ConfigItemType type, const QString &value, const QStringList &options)
{
    switch (type) {
    case Label: {
        QLabel *label = new QLabel(value);
        label->setObjectName("configValueLabel");
        return label;
    }
    case LineEdit: {
        QLineEdit *edit = new QLineEdit();
        edit->setText(value);
        edit->setObjectName("configLineEdit");
        return edit;
    }
    default:
        return nullptr;
    }
}

void ConfigItemWidget::connectWidgetSignals(QWidget *widget, const QString &name)
{
    if (!widget) return;
    
    ConfigItem *item = m_configItemMap.value(name);
    if (!item) {
        qWarning() << "ConfigItem not found for name:" << name;
        return;
    }
    
    switch (item->type) {
    case LineEdit: {
        QLineEdit *edit = qobject_cast<QLineEdit*>(widget);
        if (edit) {
            connect(edit, &QLineEdit::textChanged, this, &ConfigItemWidget::onValueChanged);
        }
        break;
    }
    default:
        break;
    }
}

void ConfigItemWidget::onValueChanged()
{
    // 找到发送信号的控件
    QWidget *sender = qobject_cast<QWidget*>(QObject::sender());
    if (!sender) return;
    
    // 找到对应的配置项
    for (ConfigItem *item : m_configItems) {
        if (item->widget == sender) {
            QString newValue = getValue(item->name);
            emit valueChanged(item->name, newValue);
            break;
        }
    }
}